#include "stmshow.h"
#include "ui_stmshow.h"

STMShow::STMShow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::STMShow)
{
    ui->setupUi(this);
    setupRealtimeDataDemo(ui->customPlot);
    ui->customPlot->replot();

    //        ui->checkBox_temp->setChecked(true);
    //        ui->checkBox_hui->setChecked(true);
    ui->pushButton_Light->setStyleSheet(QPushButton_Light_STYTLE_CLOSE);
    ui->pushButton_Light->setCheckable(true);
    ui->pushButton_Light->setText("照明关");
    connect(ui->pushButton_Light,SIGNAL(clicked()),this,SLOT(pushButtonLight()));
    ui->pushButton_Fan->setStyleSheet(QPushButton_Fan_STYTLE_CLOSE);
    ui->pushButton_Fan->setCheckable(true);
    ui->pushButton_Fan->setText("马达关");
    connect(ui->pushButton_Fan,SIGNAL(clicked()),this,SLOT(pushButtonFan()));
    connect(this,SIGNAL(realtimeDatasignal(double)),this,SLOT(realtimeDataSlot(double)));
}

STMShow::~STMShow()
{
    delete ui;
}
void STMShow::dataUpSlot(const QByteArray &message)
{
    QString messageString = QString::fromUtf8(message);
    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(message,&jsonError);
    if (!jsonDoc.isNull() && (jsonError.error == QJsonParseError::NoError))
    {
        //qDebug() << "Received message:" << messageString;
        QJsonObject jsonObj = jsonDoc.object();

        // 访问顶层字段
        int type = jsonObj["type"].toInt();
        int result = jsonObj["result"].toInt();
        qDebug() <<"type:" <<type;
        qDebug()<<"result:" <<result;
        // 访问嵌套的JSON对象
        QJsonArray dataArray = jsonObj["data"].toArray();
        for (const QJsonValue &value : dataArray) {
            QJsonObject itemObj = value.toObject();
            int key = itemObj["key"].toInt();

            QString val = itemObj["val"].toString();
            double temperture=0.0;
            switch (key) {
            case 3:
                ui->etcdata->setText(val);
                break;
            case 5:
                ui->temdata->setText(val);
                temperture=val.toDouble();
                qDebug()<<"111:"<<temperture;
                emit realtimeDatasignal(temperture);
                break;
            case 6:
                ui->humdata->setText(val);
                break;
            default:
                break;
            }

        }

    }}
//画图初始化
void STMShow::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
    //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
    //#endif
    //demoName = "Real Time Data Demo";

    // include this section to fully disable antialiasing for higher performance:
    /*
  customPlot->setNotAntialiasedElements(QCP::aeAll);
  QFont font;
  font.setStyleStrategy(QFont::NoAntialias);
  customPlot->xAxis->setTickLabelFont(font);
  customPlot->yAxis->setTickLabelFont(font);
  customPlot->legend->setFont(font);
  */
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(QColor(248, 52, 12)));
    customPlot->graph(0)->setName("温度");

    //  customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
    //  customPlot->graph(0)->setAntialiasedFill(false);
    //  customPlot->addGraph(); // red line
    //  customPlot->graph(1)->setPen(QPen(Qt::red));
    //  customPlot->graph(1)->setName("hui");
    //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));

    QLinearGradient plotGradient;
    plotGradient.setStart(0, 0);
    plotGradient.setFinalStop(0, 350);
    plotGradient.setColorAt(0, QColor(255, 255, 255));
    plotGradient.setColorAt(1, QColor(0, 102, 255));
    customPlot->setBackground(plotGradient);
    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(2);
    customPlot->axisRect()->setupFullAxesBox();

    // make left and bottom axes transfer their ranges to right and top axes:
    //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
    connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
    dataTimer.start(350); // Interval 0 means to refresh as fast as possible
    customPlot->legend->setVisible(true);



}

void STMShow::realtimeDataSlot(double temperture)
{
    //key的单位是秒
    double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
//    qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
    //double value0 = qrand() % 100;
    //    double value1 = qrand() % 80;
    //    if (ui->checkBox_temp->isChecked())
    ui->customPlot->graph(0)->addData(key,temperture );//添加数据1到曲线1
    //    if (ui->checkBox_hui->isChecked())
    //        ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2
    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
    ui->customPlot->graph(0)->removeDataBefore(key-8);
    //    ui->customPlot->graph(1)->removeDataBefore(key-8);

    //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
    //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
    ui->customPlot->graph(0)->rescaleValueAxis();
    //    ui->customPlot->graph(1)->rescaleValueAxis(true);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
    //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
    ui->customPlot->xAxis->setRange(key+0.25, 8, Qt::AlignRight);//设定x轴的范围
    ui->customPlot->replot();
}


void STMShow::pushButtonLight()
{
    //QJsonObject root;
    if(ui->pushButton_Light->isChecked())
    {
        ui->pushButton_Light->setStyleSheet(QPushButton_Light_STYTLE_OPEN);
        ui->pushButton_Light->node.data_type="1";
        ui->pushButton_Light->setText("照明开");
    }
    else if(!ui->pushButton_Light->isChecked())
    {
        ui->pushButton_Light->setStyleSheet(QPushButton_Light_STYTLE_CLOSE);
        ui->pushButton_Light->node.data_type="0";
        ui->pushButton_Light->setText("照明关");
    }
    QJsonObject node_data;
    QJsonObject node_data_data;
    QJsonDocument document;
    ui->pushButton_Light->node.type=2;
    ui->pushButton_Light->node.key=9;
    node_data.insert("type",ui->pushButton_Light->node.type);
    node_data_data.insert("key",ui->pushButton_Light->node.key);
    node_data_data.insert("val",ui->pushButton_Light->node.data_type);
    node_data.insert("data",QJsonValue(node_data_data));
    document.setObject(node_data);
    QByteArray bytearray = document.toJson(QJsonDocument::Compact);
    QMQTT::Message message;
    message.setPayload(bytearray);
    message.setTopic("/app/data/down");
    GlobalVal::mqtt->publish(message);
}
void STMShow::pushButtonFan()
{
    if(ui->pushButton_Fan->isChecked())
    {
        ui->pushButton_Fan->setStyleSheet(QPushButton_Fan_STYTLE_OPEN);
        ui->pushButton_Fan->node.data_type="1";
        ui->pushButton_Fan->setText("马达开");
    }
    else if(!ui->pushButton_Fan->isChecked())
    {
        ui->pushButton_Fan->setStyleSheet(QPushButton_Fan_STYTLE_CLOSE);
        ui->pushButton_Fan->setText("马达关");
        ui->pushButton_Fan->node.data_type="0";
    }
    QJsonObject node_data;
    QJsonObject node_data_data;
    QJsonDocument document;
    ui->pushButton_Fan->node.type=2;
    ui->pushButton_Fan->node.key=8;
    node_data.insert("type",ui->pushButton_Fan->node.type);
    node_data_data.insert("key",ui->pushButton_Fan->node.key);
    node_data_data.insert("val",ui->pushButton_Fan->node.data_type);
    node_data.insert("data",QJsonValue(node_data_data));
    document.setObject(node_data);
    QByteArray bytearray = document.toJson(QJsonDocument::Compact);
    QMQTT::Message message;
    message.setPayload(bytearray);
    message.setTopic("/app/data/down");
    GlobalVal::mqtt->publish(message);
}

void STMShow::flashSlot()
{
    QJsonObject node_data;
    QJsonDocument document;
    ui->pushButton_flash->node.type=1;
    ui->pushButton_flash->node.limit="all";
    node_data.insert("type",ui->pushButton_flash->node.type);
    node_data.insert("limit",ui->pushButton_flash->node.limit);
    document.setObject(node_data);
    QByteArray bytearray = document.toJson(QJsonDocument::Compact);
    QMQTT::Message message;
    message.setPayload(bytearray);
    message.setTopic("/app/data/down");
    GlobalVal::mqtt->publish(message);

}


